#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:1静态web服务器.py
# author: 马国鑫
# datetime:2022/4/18 21:49
# software: PyCharm

"""
this is function  description 
"""

# import module your need

import socket
import time
import multiprocessing
import sys


class WebServer(object):
    # 初始化方法
    def __init__(self,  port=8080):
        # 创建电话
        self.tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # 端口复用
        self.tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)

        # 绑定地址
        self.tcp_server_socket.bind(("", int(port)))

        # 设置监听
        self.tcp_server_socket.listen(128)

    @staticmethod
    def handler_client_request(client_socket):
        """处理客户端请求，和浏览器处理交互"""
        recv_data = client_socket.recv(1000000)

        if len(recv_data) == 0:
            print('客户端关闭')
            return

        recv_data = recv_data.decode()
        print(recv_data)

        # 对请求报文进行切割
        path_list = recv_data.split(' ')
        # print(path_list)
        # 请求资源路径
        request_path = path_list[1]

        # 异常捕获，防止出现异常服务器直接崩溃
        try:
            # 打开资源文件,二进制打开
            f = open('./static' + request_path, 'rb')
            # 存放了图片资源
            file_data = f.read()
            f.close()
        except Exception as e:
            # 证明文件不存在
            # 浏览器访问的资源不存在
            print("异常信息", e)
            # 访问不成功的情况下响应报文
            response_line = "HTTP/1.1 404 NOT FOUND\r\n"
            response_header = "server:py1.0\r\n"
            response_body = "not found i am sorry"
            response_data = response_line + response_header + "\r\n" + response_body
            # 发送数据
            client_socket.send(response_data.encode())
        else:
            # 浏览器能够找到
            # 组装响应报文
            # 响应行
            response_line = "HTTP/1.1 200 OK\r\n"
            response_header = "server:py1.0\r\n"
            response_body = file_data

            response_data = (response_line + response_header + "\r\n").encode() + response_body

            # 发送数据
            client_socket.send(response_data)
            time.sleep(1000)
            # 关闭
            client_socket.close()


    def start(self):
        while True:
            # 等待接受
            client_socket, addr = self.tcp_server_socket.accept()
            # 创建多进程
            multiprocessing.Process(target=self.handler_client_request, args=(client_socket,)).start()



if __name__ == '__main__':
    # 获取动态端口
    if len(sys.argv) != 2:
        print('正确的格式 python3 文件名 端口号')
    else:
        port = sys.argv[1]
    web_server = WebServer(int(port))
    web_server.start()
